import base64
import os
from configparser import ConfigParser

from Crypto.Cipher import PKCS1_v1_5 as Cipher_pkcs1_v1_5
from Crypto.PublicKey import RSA

from utils.loggings import loggings

os.chdir(os.path.dirname(os.path.dirname(__file__)))

CONFIG_DIR = "config/develop_config.conf"
CONFIG = ConfigParser()
CONFIG.read(CONFIG_DIR, encoding='utf-8')


class RSAEncryptionDecryption(object):
    """
    用于解密前端的密码
    """

    public_key = CONFIG['RSA']['public_key']
    private_key = CONFIG['RSA']['private_key']

    # RSA加密
    @classmethod
    def encrypt(cls, message):

        # 数据类型也可以这样转换成byte
        # bytes(message, "utf-8")

        # 导入配置文件的公钥
        public_key = RSA.importKey(cls.public_key)

        # 生成对象
        cipher = Cipher_pkcs1_v1_5.new(public_key)

        # 通过生成的对象加密message明文，在python3中加密的数据必须是bytes类型的数据，不能是str类型的数据
        cipher_text = base64.b64encode(cipher.encrypt(message.encode("utf-8")))

        return cipher_text

    @classmethod
    def _format_key(cls, key_str):
        """格式化密钥字符串"""
        try:
            # 1. 确定密钥类型
            if "PRIVATE" in key_str:
                header = "-----BEGIN RSA PRIVATE KEY-----"
                footer = "-----END RSA PRIVATE KEY-----"
            else:
                header = "-----BEGIN PUBLIC KEY-----"
                footer = "-----END PUBLIC KEY-----"
            
            # 2. 提取密钥内容
            content = key_str[key_str.index(header) + len(header):key_str.index(footer)]
            content = content.strip()
            
            # 3. 每64个字符添加换行
            chunks = [content[i:i+64] for i in range(0, len(content), 64)]
            formatted_content = '\n'.join(chunks)
            
            # 4. 组装完整的密钥
            return f"{header}\n{formatted_content}\n{footer}"
            
        except Exception as e:
            loggings.error(f"Key formatting error: {str(e)}")
            return key_str  # 如果格式化失败，返回原始字符串

    # RSA 解密
    @classmethod
    def decrypt(cls, cipher_text):
        """解密函数"""
        try:
            # 1. 检查输入
            if not cipher_text:
                raise ValueError("Empty cipher text")
            
            # 2. 格式化私钥
            private_key_str = cls._format_key(cls.private_key)
            
            # 3. 导入私钥
            try:
                private_key = RSA.importKey(private_key_str)
            except ValueError as e:
                loggings.error(f"Invalid private key format: {str(e)}")
                raise ValueError(f"Invalid private key format: {str(e)}")
                
            cipher = Cipher_pkcs1_v1_5.new(private_key)
            
            # 4. Base64解码
            try:
                decoded = base64.b64decode(cipher_text)
            except Exception as e:
                raise ValueError(f"Base64 decode failed: {str(e)}")
            
            # 5. RSA解密
            try:
                text = cipher.decrypt(decoded, "ERROR")
            except Exception as e:
                raise ValueError(f"RSA decrypt failed: {str(e)}")
            
            # 6. UTF-8解码
            try:
                result = text.decode("utf-8")
            except Exception as e:
                raise ValueError(f"UTF-8 decode failed: {str(e)}")
            
            return result

        except Exception as e:
            loggings.exception(1, f"Decryption failed: {str(e)}")
            return None


